package com.zhang.warehouse.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.common.util.result.R;
import com.zhang.common.util.result.RUtils;
import com.zhang.common.util.time.TimeUtils;
import com.zhang.warehouse.dto.FinishDto;
import com.zhang.warehouse.dto.MergeDto;
import com.zhang.warehouse.dto.purchaseDetailsItem;
import com.zhang.warehouse.entity.Purchase;
import com.zhang.warehouse.entity.PurchaseDetail;
import com.zhang.warehouse.entity.WareSku;
import com.zhang.warehouse.mapper.PurchaseMapper;
import com.zhang.warehouse.service.IPurchaseDetailService;
import com.zhang.warehouse.service.IPurchaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.warehouse.service.IWareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购信息 服务实现类
 * </p>
 *
 * @author 创世神
 * @since 2023-10-14
 */
@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase> implements IPurchaseService {
    @Autowired
    private IPurchaseDetailService purchaseDetailService;
    @Autowired
    private IWareSkuService wareSkuService;


    @Override
    @Transactional
    public void receivePurchase(List<Long> purchaseIds) {

        /*确认当前采购单是新建(0)或者已分配状态(1)
         * 查看分配人员是否是当前领取人*/
        List<Purchase> collect = purchaseIds.stream().map(purchaseId -> {
            Purchase purchase = getById(purchaseId);
            return purchase;
        }).filter(purchase -> {
            if ((purchase.getStatus() == 0 || purchase.getStatus() == 1) && (Long.valueOf(StpUtil.getLoginIdAsLong()).equals(purchase.getAssigneeId()))) {
                return true;
            } else return false;
        }).map(item -> {
            item.setStatus(2);
            item.setUpdateTime(TimeUtils.getLocalDateTimeStr());
            return item;
        }).collect(Collectors.toList());
        updateBatchById(collect);
        /*改变采购项的状态*/
        for (Long purchaseId : purchaseIds) {
            List<PurchaseDetail> purchaseDetails = purchaseDetailService.getListByPurchaseId(purchaseId);
            purchaseDetails.forEach(item -> {
                item.setStatus(2);//设为正在采购
            });
            purchaseDetailService.updateBatchById(purchaseDetails);
        }
    }

    @Override
    public R getpurchasePageList(Map searchDto) {
        QueryWrapper<Purchase> wrapper = new QueryWrapper<>();
        String pageNum = (String) searchDto.get("pageNum");
        String pageSize = (String) searchDto.get("pageSize");
        String status = (String) searchDto.get("status");
        if (!StrUtil.isBlank(status)) {
            wrapper.eq("status", status);
        }
        String searchValue = (String) searchDto.get("searchValue");
        if (!StrUtil.isBlank(searchValue)) {
        }
        if (!(StrUtil.isBlank(pageNum) || StrUtil.isBlank(pageSize))) {
            Page<Purchase> page = page(new Page<Purchase>(Integer.valueOf(pageNum), Integer.valueOf(pageSize)), wrapper);
            return RUtils.successData(page);
        }
        List<Purchase> list = list(wrapper);
        return RUtils.successData(list);
    }


    @Override
    public void mergePurchaseDetail(MergeDto mergeDto) {
        List<PurchaseDetail> purchaseDetails = purchaseDetailService.listByIds(mergeDto.getPurchaseDetailIds());
        Long purchaseId = mergeDto.getPurchaseId();
        if (purchaseId == null) {
            Purchase purchase = new Purchase();
            purchase.setCreateTime(TimeUtils.getLocalDateTimeStr());
            purchase.setStatus(0);
//            计算总金额
            BigDecimal totalAmount = purchaseDetails.stream()
                    .map(PurchaseDetail::getPrice) // 将每个PurchaseDetail对象映射为其price值
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            purchase.setAmount(totalAmount);
            save(purchase);
            purchaseId = purchase.getId();
        }
        Long finalPurchaseId = purchaseId;
        /*先判断这些采购项的状态是不是新建或者分配*/
        List<PurchaseDetail> collect = purchaseDetails.stream().filter(item -> {
            if (item.getStatus() == 0 || item.getStatus() == 1) {
                return true;
            } else return false;
        }).map(item -> {
            PurchaseDetail purchaseDetail = new PurchaseDetail();
            purchaseDetail.setId(item.getId());
            purchaseDetail.setPurchaseId(finalPurchaseId);
            purchaseDetail.setStatus(1);
            return purchaseDetail;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);
    }

}
